import os
import sys
import re
import time

sys.path.insert(0, '.')

fileListName = 'vfl_sim'
logFileName  = 'sim_log'

import simlist
tbList    = simlist.tbList
tbIncdir  = simlist.tbIncdir
rtlList   = simlist.rtlList
rtlIncdir = simlist.rtlIncdir
pymode    = simlist.pymode

try:
  runSim   = int(sys.argv[1])
  runVerdi = int(sys.argv[2])
  runSeed  = int(time.time())
except:
  print('''
%s runSim runVerdi [runSeed]
    runSim   : 1 sim run  0 not sim
    runVerdi : 1 open Verdi  0 not open
    runSeed  : use user set , if not use time.time()
''' % (
  sys.argv[0],
  ))
  sys.exit(0)

try:
  runSeed = int(sys.argv[3])
except:
  pass

def GenerateFileList(fileListName):
  with open(fileListName,"w") as f:

    for fileListPath in tbIncdir:
      f.write('+incdir+../../../'+fileListPath+'\n')
    f.write('\n')

    for fileListPath in rtlIncdir:
      f.write('+incdir+../../../'+fileListPath+'\n')
    f.write('\n')

    for fileListPath in tbList:
      f.write('../../../'+fileListPath+'\n')
    f.write('\n')

    for fileListPath in rtlList:
      f.write('../../../'+fileListPath+'\n')
    f.write('\n')

def RunSim(seed, logFileName, fileListName):
  print("vcs -R -sverilog -file -add -fsdb -debug_all -CFLAGS -g -timescale=1ns/10ps +notimingcheck +nospecify -ntb_opts +ntb_random_seed=%d +SEED=%d -l %s -f %s >> `tty`" %(
        seed,
        seed,
        logFileName,
        fileListName,
        ))
  #os.popen("vcs -R -sverilog -file -add -fsdb -debug_all -CFLAGS -g -timescale=1ns/10ps +notimingcheck +nospecify -ntb_opts +ntb_random_seed=%d +SEED=%seed -l %s -f %s >> `tty`" %(
  os.popen("vcs -R -sverilog -P /opt/Synopsys/Verdi2015/share/PLI/VCS/linux64/novas.tab /opt/Synopsys/Verdi2015/share/PLI/VCS/linux64/pli.a -full64 -debug_all -CFLAGS -g -timescale=1ns/10ps +ntb_random_seed=%d -l %s -f %s >> `tty`" %(
        seed,
        logFileName,
        fileListName,
        ))

def RunVerdi(fileListName):
  print("verdi -sv -f %s & >> `tty`" %(
        fileListName,
        ))
  os.popen("verdi -sv -f %s >> `tty`" %(
        fileListName,
        ))

if __name__ == '__main__':
  if runSim:
    GenerateFileList(
        fileListName,
        )
    pym = pymode()

    pym.SetSeed(runSeed)
    pym.Run()

    RunSim(
        runSeed,
        logFileName,
        fileListName,
        )
  if runVerdi:
    RunVerdi(
        fileListName,
        )
